<?php

/* v3.1.0  */

class Home extends M_Controller
{

    /**
     * 构造函数
     */
    public function __construct()
    {
        parent::__construct();
        if ((int)$this->uid < 1) {
            apiSuccess(-4001, '请登录');
        }
    }

    /**
     * 首页
     */
    public function index()
    {
        // 登录验证
        $url = dr_member_url('login/index', array('backurl' => urlencode(dr_now_url())));
        !$this->uid && $this->member_msg(L('会话超时，请重新登录') . $this->models('member/login')->logout(), $url);

        $this->load->library('dip');
        $this->template->assign(array(
            'index' => 1,
        ));
        $this->template->display(IS_AJAX ? 'main.html' : 'index.html');
    }

    // 修改用户信息
    public function editMember()
    {
        try {
            $data = $this->input->post();
            if (!is_valid('email', $data['email']) && $data['email']) {
                throw new Exception('邮箱地址错误');
            }
            $formData = [
                'name' => $data['name'],
                'avatar' => (int)$data['avatar'],
                'email' => $data['email'],
                'introduce' => $data['introduce']
            ];
            if (empty($this->models('member')->upMember(array_filter($formData), $this->uid))) {
                apiSuccess(0, '修改失败');
            }
            apiSuccess(1, '修改成功');
        } catch (Exception $e) {
            apiSuccess(0, $e->getMessage());
        }

    }

    // 收藏列表
    public function myCollection()
    {
        if (isset($this->uid) && $this->uid > 0) {
            $page = max($_GET['page'], 1);
            $pageSize = (int)$_GET['pageSize'] ?: 10;
            $result = $this->models('member')->myCollection($this->uid, $page, $pageSize);
            apiSuccess(1, 'success', [
                'list' => array_map(function (&$item) {
                    return $this->models('favorite')->favoriteTransfer($item);
                }, $result),
                'end' => count($result) < $pageSize
            ]);
        } else {
            apiSuccess(-4001, '请登录');
        }
    }

    // 查看我的订单的支付详情
    public function payInfo()
    {
        try {
            if ((int)$this->uid < 1) {
                apiSuccess(-4001, '请登录');
            }
            $id = decrypt($this->input->get('id'), 'mutaoinc');
            if ((int)$id < 0) {
                throw new Exception('参数错误');
            }
            $info = $this->models('system/pay')->getItem($id, 'uid,status,inputtime');
            if ($info['uid'] <> $this->uid) {
                throw new Exception('请查看自己的订单');
            }
            if ($info['inputtime'] - 20 > time()) {
                throw new Exception('订单已失效');
            }
            apiSuccess(1, 'success', ['status' => true, 'info' => $info]);
        } catch (Exception $e) {
            apiSuccess(0, $e->getMessage());
        }
    }

    /**
     * 1我的购买藏品列表
     * 2开盲盒的商品列表
     */
    public function myFavorite()
    {
        $page = max($_GET['page'], 1);
        $pageSize = (int)$_GET['pageSize'] ?: 10;
        $type = $this->input->get('type');
        $status = null;
        if ($type) {
            switch ($type) {
                case 1:
                    $status = 1;
                    break;
                case 2:
                    $status = ['2', '4'];
                    break;
                case 3:
                    $status = 3;
                default:
                    break;
            }
        }
        $param = [
            'uid' => $this->uid,
            'type' => $status
        ];
        $result = $this->models('favorite')->buyList(array_filter($param), $page, $pageSize);
        apiSuccess(1, 'success', [
            'list' => array_map(function (&$item) {
                return $this->models('favorite')->favoriteTransfer($item, 'my');
            }, $result),
            'end' => count($result) < $pageSize
        ]);
    }

    // 我购买的盲盒列表
    public function myBox()
    {
        $page = max($_GET['page'], 1);
        $pageSize = (int)$_GET['pageSize'] ?: 10;
        $type = $this->input->get('type');
        $rule = [
            '1' => ['order_status' => 1, 'pay_status' => 0],
            '2' => ['order_status' => 1, 'pay_status' => 3],
            '3' => ['order_status' => 3, 'pay_status' => 3],
        ];
        $param = ['buy_uid' => $this->uid, 'mid' => 'box'];
        if(isset($rule[$type])){
            $param +=  $rule[$type];
        }
        $result = $this->models('favorite')->boxOrderList($param, $page, $pageSize);
        if ($result) {
            $oidArr = array_column($result, 'id');
            $goodList = $this->models('favorite')->goodsList($oidArr);
            foreach ($result as &$item) {
                foreach ($goodList as &$good) {
                    $good['thumb'] = dr_thumb($good['thumb'], 500, 500);
                    if ($good['oid'] == $item['id']) {
                        $item['goods'] = $good;
                    }
                }
            }
        }
        apiSuccess(1, 'success', [
            'list' => $result ? array_map(function (&$item) {
                return $this->models('favorite')->orderTransfer($item);
            }, $result) : [],
            'end' => $pageSize > count($result)
        ]);
    }

    // 实名认证
    public function realName()
    {
        try {
            $data = $this->input->post();
            if (empty($data['name']) || empty($data['phone']) || empty($data['id_card'])) {
                throw new Exception('请输入完整内容');
            }
            if ($this->member['real_status'] == 1) {
                throw new Exception('您已认证,请勿再次操作');
            }
            $filed = [
                'phone' => $data['phone'],
                'name' => $data['name'],
                'id_card' => $data['id_card']
            ];
            if (!is_valid('phone', $filed['phone'])) {
                throw new Exception('手机号格式不正确');
            }
            require_once WEBPATH . 'web/libraries/Real/Authentication.php';
            $result = (new Authentication($filed))->realName()['result'];
            $this->db->trans_begin();
            if (empty($this->models('member')->upMember(['real_status' => 1], $this->uid))) {
                throw new Exception('请稍后重试');
            }
            $result['uid'] = $this->uid;
            if (empty($this->models('member')->realName($result))) {
                throw new Exception('认证失败,稍后重试');
            }
            $this->db->trans_commit();
            apiSuccess(1, '您已完成实名认证');
        } catch (Exception $e) {
            if ($e->getCode() == 1) {
                $this->db->trans_rollback();
            }
            apiSuccess(0, $e->getMessage());
        }
    }

    // 充值
    public function recharge()
    {
        try {
            $price = $this->input->post('price');
            if ($price < 1) {
                throw new Exception('最少充值1元');
            }
            if (!preg_match('/^[1-9]\d*$/', $price)) {
                throw new Exception('请输入正整数');
            }
            $oid = $this->models('member')->rechargeOrder(['uid' => $this->uid, 'value' => $price]);
            if ($oid < 1) {
                throw new Exception('生成订单失败');
            }
            $payID = $this->models('system/pay')->create($this->uid, $price, 'recharge', $oid, "充值{$price}");
            apiSuccess(1, 'success', ['oid' => $oid, 'payId' => encrypt($payID, 'mutaoinc')]);
        } catch (Exception $e) {
            apiSuccess(0, $e->getMessage());
        }
    }

    // 绑定团队
    public function bindTeam()
    {
        try {
            $data = $this->input->post();
            if (!$data['team_code']) {
                throw new Exception('请输入团队码');
            }
            $codeInfo = $this->models('member')->uidInfo(['randcode' => $data['team_code']], 'uid');
            if (empty($codeInfo)) {
                throw new Exception('无效码');
            }
            if ($codeInfo['uid'] == $this->uid) {
                throw new Exception('请勿绑定自己的码');
            }
            $formData = [
                'team_code' => $data['team_code'],
                'team_time' => time()
            ];
            if (empty($this->models('member')->upMember($formData, $this->uid))) {
                apiSuccess(0, '绑定失败');
            }
            apiSuccess(1, '绑定成功');
        } catch (Exception $e) {
            apiSuccess(0, $e->getMessage());
        }
    }

    // 我的团队
    public function myTeam()
    {
        $page = max($_GET['page'], 1);
        $pageSize = (int)$_GET['pageSize'] ?: 10;
        if ((int)$this->uid < 1) {
            apiSuccess(-4001, '请登录');
        }
        $result = $this->models('member/withdrawal')->myTeam($this->member['randcode'], $page, $pageSize);
        apiSuccess(1, 'success', [
            'list' => array_map(function (&$item) {
                return $this->models('member/withdrawal')->myTeamTransfer($item);
            }, $result),
            'end' => $pageSize > count($result),
            'code' => $this->member['randcode']
        ]);
    }

}